from flask import Blueprint, request,jsonify,redirect

from utils.redis import r
from utils.comm import get_data
from flask_mail import Mail,Message
from flask import current_app as app

import re
from db import db1
bp_jyuser = Blueprint('jyuser', __name__)


def testmail(tou,ren,a):
    mail = Mail(app)
    msg = Message(tou,sender='qq1143028552@163.com',recipients=[ren])#发件人，收件人
    msg.body = a
    mail.send(msg)

@bp_jyuser.route('/useradd',methods=['POST','GET'])
def useradd():
    if request.method=='POST':
        data = get_data()
        mobie = data['mobie']
        m = data['email']
        reg = re.match('^1[3-9]\d{9}$',mobie)
        pat = re.match('^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$',m)
        # try:
        if reg and pat:
            sql1 = '''select mobie,email from users where mobie="%s"'''%(data['mobie'])
            sql2 = '''select email from users where email="%s"'''%(data['email'])
            d = db1.find(sql1)
            x = db1.find(sql2)
            if not (d and x):
                sql = '''insert into users(name,password,email,mobie) 
                values("%s","%s","%s","%s")'''%(data['name'],data['password'],data['email'],data['mobie'])
                db1.update(sql)

                testmail('欢迎使用163', data['email'], "欢迎使用，点击以下<a href='http://localhost:5000/jyuser/validEmail?email=" + data[
                    'email'] + "'>链接</a>验证")
                # redis存过期时间 key 邮箱 value 当前时间  过期时间

                return jsonify({"code":200})
            else:
                return jsonify({"code":10012,'mes':'手机号或邮箱已注册'})
        else:
            return jsonify({"code":10010,'mes':'手机号不正确或邮箱不正确'})
        # except:
        #     return jsonify({"code":10011,'mes':'网络走丢了'})

@bp_jyuser.route('/validEmail')
def validEmail():
    #获取email
    email = request.args.get('email')
    #更新用户表
    sql = "update users set zt=1 where email='%s'"%(email)
    db1.update(sql)
    return redirect('http://localhost:8888')

